package com.phpxiu.app.view.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.phpxiu.app.api.callback.MsgCountManager;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.Permission;
import com.phpxiu.app.model.UploadResultInfo;
import com.phpxiu.app.model.UserCenter;
import com.phpxiu.app.model.card.RoomCardInfo;
import com.phpxiu.app.model.card.RoomCardRank;
import com.phpxiu.app.model.event.OnLvUp;
import com.phpxiu.app.model.event.OnRefreshFollowCount;
import com.phpxiu.app.model.event.OnTicketExchanged;
import com.phpxiu.app.model.event.OnUpdateBalance;
import com.phpxiu.app.model.event.UserEditEvent;
import com.phpxiu.app.model.response.UserCenterMode;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.presenters.viewinterface.UploadView;
import com.phpxiu.app.pulltorefresh.PullToRefreshScrollView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.upload.TUploadHelper;
import com.phpxiu.app.utils.FileManager;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.C2CConversationManager;
import com.phpxiu.app.view.Main;
import com.phpxiu.app.view.PicturePreview;
import com.phpxiu.app.view.RoomFansRank;
import com.phpxiu.app.view.UIBase;
import com.phpxiu.app.view.UserAccount;
import com.phpxiu.app.view.UserFollow;
import com.phpxiu.app.view.UserFans;
import com.phpxiu.app.view.UserGrade;
import com.phpxiu.app.view.UserHome;
import com.phpxiu.app.view.UserIncoming;
import com.phpxiu.app.view.UserInfoEdit;
import com.phpxiu.app.view.UserLiveHistory;
import com.phpxiu.app.view.UserSetting;
import com.phpxiu.app.view.custom.FrescoImageView;
import com.phpxiu.app.view.custom.WindowLayout;
import com.phpxiu.app.view.dialog.PhotoOptionMenus;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * Created by WuJinZhou on 2016/5/5.
 */
public class UserFragment extends BaseFragment implements PullToRefreshView.OnRefreshListener<ScrollView>,View.OnClickListener,UploadView,Observer {
    private final static ForegroundColorSpan SPAN=new ForegroundColorSpan(Color.parseColor("#7fFFFFFF"));
    public final static String TAG="UserFragment";
    private final static int HANDLE_REFRESH_HEAD_VIEW=0x1;
    private final static int HANDLE_REFRESH_NICK_VIEW=0x2;
    private final static int HANDLE_REFRESH_SEX_VIEW=0x3;
    private final static int HANDLE_REFRESH_FOLLOW=0x4;//刷新关注数
    private final static int HANDLE_UPDATE_LEVEL=0x5;//更新等级
    private final static int HANDLE_UPDATE_TICKETS=0x6;//更新礼券数
    private final static int HANDLE_UPDATE_DIAMONDS=0x7;//更新钻数
    public final static int HANDLER_REFRESH_MSG_COUNT=0x115;//刷新未读消息数量
    private UserCenter mInfo;
    private RoomCardInfo mUser;

    private int followCount=0;//当前关注数
    private int level=1;//等级
    private long tickets=0;//收入礼券数
    private long diamonds=0;//钻石数，付费功能花费

    private int mScreenWidth;
    private boolean isInit=true;//是否需要初始化数据
    private PullToRefreshScrollView scrollView;
    private WindowLayout mainView;
    private TextView costView;//消费钻石数据
    private SpannableStringBuilder costText=new SpannableStringBuilder();
    private FrescoImageView avatarView;//头像
    private Uri localAvatar=null;
    private PhotoOptionMenus photoMenus;
    private TextView IDView;//显示直播ID
    private TextView nickView;
    private ImageView sexView;
    private FrescoImageView LVIconView;
    private TextView followView;
    private TextView fansView;
    private TextView introView;

    private TextView contributeLabel;
    private FrescoImageView userNo1,userNo2,userNo3;//粉丝贡献前三名
    private TextView historyLabel;
    private TextView levelLabel;
    private TextView levelView;//显示等级数
    private TextView incomeLabel;
    private TextView incomeView;//显示收入数
    private TextView accountLabel;
    private TextView diamondView;//显示账户钻石数
    private TextView settingsLabel;

    private RelativeLayout loadingBox;
    private ImageView loadingImage;
    private AnimationDrawable uploadAni;
    private TUploadHelper uploader;

    private RelativeLayout openC2CList;
    private TextView countView;
    private long msgCount=0;

    private SpannableStringBuilder followLink=new SpannableStringBuilder();
    private SpannableStringBuilder fansLink=new SpannableStringBuilder();
    private String followTxt,fansTxt;

    private OKHttpParam param;

    public static BaseFragment builder(String arg){
        UserFragment fragment=new UserFragment();
        Bundle b = new Bundle();
        b.putString(ARG,arg);
        fragment.setArguments(b);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        followTxt=getString(R.string.ui_user_follow_title);
        fansTxt=getString(R.string.ui_user_fans_label);
        mScreenWidth=(int) KKYApp.getInstance().screenWidth;
        uploader=new TUploadHelper(getActivity(),this,"avatar");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.user_fragment,null);
        mainView=(WindowLayout)rootView.findViewById(R.id.main_layout_view);
        View topView=rootView.findViewById(R.id.user_fragment_top_view);
        RelativeLayout.LayoutParams params=(RelativeLayout.LayoutParams)topView.getLayoutParams();
        int topViewHeight=(52*mScreenWidth)/75;
        params.height=topViewHeight;
        topView.setLayoutParams(params);
        init();
        initMsgCount();
        return rootView;
    }

    @Override
    public void onInit(UIBase act) {
        if(isInit) {
            this.act = act;
            request();
        }
    }
    /**
     * 消息数量维护
     */
    private void initMsgCount(){
        MsgCountManager.getInstance().addObserver(this);
        MsgCountManager.getInstance().refreshMsgCount();
    }

    /**
     *更新消息数量
     * @param observable
     * @param data
     */
    @Override
    public void update(Observable observable, Object data) {
        try {
            msgCount=(long)data;
            if(handler!=null){
                handler.sendEmptyMessage(HANDLER_REFRESH_MSG_COUNT);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 请求数据
     */
    private void request(){
        if(param==null){
            param=OKHttpParam.builder();
        }
        OKHttp.post(HttpConfig.API_GET_USER_CENTER_INFO, param.jsonParam(), TAG, new OKHttpUIHandler(UserCenterMode.class) {
            @Override
            public void onSuccess(Object model) {
                UserCenterMode m = (UserCenterMode) model;
                KKYUtil.log("用户中心数据：" + m.getResponseStr());
                if (scrollView != null) {
                    scrollView.onRefreshComplete();
                }
                refreshView(m.getData());
                isInit = false;
            }

            @Override
            public void onErr(String errMsg) {
                if(mainView!=null){
                    mainView.showTopMsg(errMsg);
                }
                if (scrollView != null) {
                    scrollView.onRefreshComplete();
                }
            }
        });
    }

    /**
     * 初始化控件对象
     */
    private void init(){
        scrollView=(PullToRefreshScrollView)rootView.findViewById(R.id.pull_refresh_scroll_view);
        scrollView.setOnRefreshListener(this);
        rootView.findViewById(R.id.user_edit_btn).setOnClickListener(this);
        costView=(TextView)rootView.findViewById(R.id.user_cost_view);
        avatarView=(FrescoImageView)rootView.findViewById(R.id.user_head_view);
        avatarView.setOnClickListener(this);
        IDView=(TextView)rootView.findViewById(R.id.user_live_id_view);
        nickView=(TextView)rootView.findViewById(R.id.user_nick);
        sexView=(ImageView)rootView.findViewById(R.id.user_sex_icon_view);
        LVIconView=(FrescoImageView)rootView.findViewById(R.id.user_lvl_icon_view);
        followView=(TextView)rootView.findViewById(R.id.user_follow_link);
        followView.setOnClickListener(this);
        fansView=(TextView)rootView.findViewById(R.id.user_fans_link);
        fansView.setOnClickListener(this);
        introView=(TextView)rootView.findViewById(R.id.intro_view);

        rootView.findViewById(R.id.profile_contribute_rank_link).setOnClickListener(this);
        userNo1=(FrescoImageView)rootView.findViewById(R.id.user_no1_view);
        userNo2=(FrescoImageView)rootView.findViewById(R.id.user_no2_view);
        userNo3=(FrescoImageView)rootView.findViewById(R.id.user_no3_view);

        loadingBox=(RelativeLayout)rootView.findViewById(R.id.loading_box);
        loadingImage=(ImageView)rootView.findViewById(R.id.loading_header_view);
        uploadAni=(AnimationDrawable)loadingImage.getBackground();
        openC2CList=(RelativeLayout)rootView.findViewById(R.id.open_chat_win);
        openC2CList.setOnClickListener(this);
        countView=(TextView)rootView.findViewById(R.id.all_c2c_conversation_un_read_count_view);

        rootView.findViewById(R.id.profile_live_history_link).setOnClickListener(this);
        rootView.findViewById(R.id.profile_level_link).setOnClickListener(this);
        rootView.findViewById(R.id.profile_income_link).setOnClickListener(this);
        rootView.findViewById(R.id.profile_account_link).setOnClickListener(this);
        rootView.findViewById(R.id.profile_settings_link).setOnClickListener(this);

        contributeLabel=(TextView)rootView.findViewById(R.id.profile_contribute_label);
        historyLabel=(TextView)rootView.findViewById(R.id.profile_live_history_label);
        levelLabel=(TextView)rootView.findViewById(R.id.profile_level_label);
        levelView=(TextView)rootView.findViewById(R.id.profile_level_view);
        incomeLabel=(TextView)rootView.findViewById(R.id.profile_income_label);
        incomeView=(TextView)rootView.findViewById(R.id.profile_income_view);
        accountLabel=(TextView)rootView.findViewById(R.id.profile_account_label);
        diamondView=(TextView)rootView.findViewById(R.id.profile_diamond_count_view);
        settingsLabel=(TextView)rootView.findViewById(R.id.profile_settings_link_label);
    }
    /**
     * 刷新视图内容
     */
    private void refreshView(UserCenter content){
        if(content==null){
            return;
        }
        mInfo=content;
        mUser=content.getInfo();
        updateMySelfInfo(content.getInfo());
        costText.clear();
        costText.append(getString(R.string.ui_user_cost_label)).append(" ").append(mUser.getSpend());
        costView.setText(costText);

        avatarView.setImageURI(Uri.parse(mUser.getAvatar()));
        IDView.setText("ID "+mUser.getUid());
        nickView.setText(mUser.getNickname());
        String sex=mUser.getSex();
        if("1".equals(sex)){
            sexView.setImageResource(R.mipmap.user_sex_icon_male);
        }else{
            sexView.setImageResource(R.mipmap.user_sex_icon_female);
        }
        if(!"".equals(mUser.getLvl())){
            LVIconView.setImageURI(Uri.parse("asset:///lvIcons/" + mUser.getLvl()+ ".png"));
        }
        try {
            followCount=Integer.parseInt(mUser.getFollownum());
        }catch (NumberFormatException e){

        }
        followLink.clear();
        followLink.append(followTxt).append(" ").append(followCount + "");
        followLink.setSpan(SPAN,0,followTxt.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        followView.setText(followLink);
        fansLink.clear();
        fansLink.append(fansTxt).append(" ").append(mUser.getFansnum());
        fansLink.setSpan(SPAN,0,fansTxt.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        fansView.setText(fansLink);
        introView.setText(mUser.getIntro());

        List<RoomCardRank>top=content.getRank();
        if(top!=null&&top.size()>0){
            switch (top.size()){
                case 1:
                    userNo1.setImageURI(Uri.parse(top.get(0).getAvatar()));
                    userNo1.setTag(top.get(0).getUid());
                    //userNo1.setOnClickListener(this);
                    //userNo2.setOnClickListener(null);
                    //userNo3.setOnClickListener(null);
                    break;
                case 2:
                    userNo1.setImageURI(Uri.parse(top.get(0).getAvatar()));
                    userNo1.setTag(top.get(0).getUid());
                    //userNo1.setOnClickListener(this);
                    userNo2.setImageURI(Uri.parse(top.get(1).getAvatar()));
                    userNo2.setTag(top.get(1).getUid());
                    //userNo2.setOnClickListener(this);
                    //userNo3.setOnClickListener(null);
                    break;
                case 3:
                    userNo1.setImageURI(Uri.parse(top.get(0).getAvatar()));
                    userNo1.setTag(top.get(0).getUid());
                    //userNo1.setOnClickListener(this);
                    userNo2.setImageURI(Uri.parse(top.get(1).getAvatar()));
                    userNo2.setTag(top.get(1).getUid());
                    //userNo2.setOnClickListener(this);
                    userNo3.setImageURI(Uri.parse(top.get(2).getAvatar()));
                    userNo3.setTag(top.get(2).getUid());
                    //userNo3.setOnClickListener(this);
                    break;
            }
        }else{
            //userNo1.setOnClickListener(null);
            //userNo2.setOnClickListener(null);
            //userNo3.setOnClickListener(null);
        }
        try {
            level=Integer.parseInt(mUser.getLvl());
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        levelView.setText(level+getString(R.string.ui_user_level_unit));
        try {
            tickets=Long.parseLong(mUser.getIncome());//当前余的票数
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        incomeView.setText(tickets+getString(R.string.ticket_unit));
        try {
            diamonds=Long.parseLong(mUser.getMoney());
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        diamondView.setText(diamonds+getString(R.string.diamond_unit));
    }

    /**
     * 刷新标签文本
     */
    private void refreshLabelViews(){
        contributeLabel.setText(getString(R.string.ui_rank_title));
        historyLabel.setText(getString(R.string.ui_profile_history_label));
        levelLabel.setText(getString(R.string.ui_profile_level_label));
        levelView.setText(level+getString(R.string.ui_user_level_unit));
        incomeLabel.setText(getString(R.string.ui_profile_income_label));
        incomeView.setText(tickets+getString(R.string.ticket_unit));
        accountLabel.setText(getString(R.string.ui_profile_account_label));
        diamondView.setText(diamonds+getString(R.string.diamond_unit));
        settingsLabel.setText(getString(R.string.ui_profile_setting_label));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.user_edit_btn:
                if(mUser!=null) {
                    Intent editUser = new Intent(getActivity(), UserInfoEdit.class);
                    editUser.putExtra(UserInfoEdit.EXTRA_PARAM_USER_KEY, mUser);
                    startActivity(editUser);
                }else{
                    mainView.showTopMsg(getString(R.string.ui_profile_loading));
                }
                break;
            case R.id.open_chat_win:
                showC2CListWin();
                break;
            case R.id.user_head_view:
                if(mUser!=null) {
                    if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
                        requestMyPermissions(Permission.REQUEST_PHOTO);
                    }else {
                        editAvatar();
                    }
                }else{
                    mainView.showTopMsg(getString(R.string.ui_profile_loading));
                }
                break;
            case R.id.user_follow_link:
                if(mUser!=null) {
                    Intent attention = new Intent(getActivity(), UserFollow.class);
                    attention.putExtra(UserFollow.EXTRA_PARAM_UID_KEY, mUser.getUid());
                    startActivity(attention);
                }else{
                    mainView.showTopMsg(getString(R.string.ui_profile_loading));
                }
                break;
            case R.id.user_fans_link:
                if(mUser!=null) {
                    Intent fans = new Intent(getActivity(), UserFans.class);
                    fans.putExtra(UserFans.EXTRA_PARAM_UID_KEY, mUser.getUid());
                    startActivity(fans);
                }else{
                    mainView.showTopMsg(getString(R.string.ui_profile_loading));
                }
                break;
            case R.id.profile_live_history_link:
                if(mUser!=null){
                    Intent video=new Intent(getActivity(), UserLiveHistory.class);
                    video.putExtra(UserLiveHistory.UID,mUser.getUid());
                    startActivity(video);
                }
                break;
            case R.id.profile_level_link:
                Intent grade=new Intent(getActivity(), UserGrade.class);
                startActivity(grade);
                break;
            case R.id.profile_income_link:
                if(mUser!=null) {
                    Intent income = new Intent(getActivity(), UserIncoming.class);
                    startActivity(income);
                }else{
                    mainView.showTopMsg(getString(R.string.ui_profile_loading));
                }
                break;
            case R.id.profile_account_link:
                if(mUser!=null) {
                    Intent account = new Intent(getActivity(), UserAccount.class);
                    long balance = 0;
                    try {
                        balance = Long.parseLong(mUser.getMoney());
                    } catch (NumberFormatException e) {

                    }
                    account.putExtra(UserAccount.EXTRA_PARAM_BALANCE_KEY, balance);
                    startActivity(account);
                }else{
                    mainView.showTopMsg(getString(R.string.ui_profile_loading));
                }
                break;
            case R.id.profile_contribute_rank_link://排行列表
                if(mUser!=null) {
                    Intent roomRank = new Intent(getActivity(), RoomFansRank.class);
                    roomRank.putExtra(RoomFansRank.EXTRA_PARAM_USER_ID_KEY, mUser.getUid());
                    roomRank.putExtra(RoomFansRank.EXTRA_PARAM_USER_TICKETS_KEY, mUser.getIncome()+ "");
                    startActivity(roomRank);
                }else{
                    mainView.showTopMsg(getString(R.string.ui_profile_loading));
                }
                break;
            case R.id.profile_settings_link:
                Intent setting = new Intent(getActivity(), UserSetting.class);
                startActivity(setting);
                break;
            case R.id.user_no1_view:
            case R.id.user_no2_view:
            case R.id.user_no3_view:
                Intent home=new Intent(getActivity(), UserHome.class);
                home.putExtra(UserHome.EXTRA_PARAM_KEY_UID,v.getTag().toString());
                startActivity(home);
                break;
            default:
                break;
        }
    }

    @Override
    public void onRefresh(PullToRefreshView<ScrollView> refreshView) {
        request();
    }

    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);
        switch (msg.what){
            case HANDLE_REFRESH_HEAD_VIEW:
                avatarView.setImageURI(Uri.parse(mUser.getAvatar()));
                break;
            case HANDLE_REFRESH_NICK_VIEW:
                nickView.setText(mUser.getNickname());
                break;
            case HANDLE_REFRESH_SEX_VIEW:
                String sex=mUser.getSex();
                if("1".equals(sex)){
                    sexView.setImageResource(R.mipmap.user_sex_icon_male);
                }else{
                    sexView.setImageResource(R.mipmap.user_sex_icon_female);
                }
                break;
            case HANDLE_REFRESH_FOLLOW:
                followLink.clear();
                followLink.append(followTxt).append(" ").append(followCount + "");
                followLink.setSpan(SPAN, 0, followTxt.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                followView.setText(followLink);
                break;
            case HANDLE_UPDATE_LEVEL:
                levelView.setText(level+getString(R.string.ui_user_level_unit));
                break;
            case HANDLE_UPDATE_TICKETS:
                incomeView.setText(tickets+getString(R.string.ticket_unit));
                break;
            case HANDLE_UPDATE_DIAMONDS:
                diamondView.setText(diamonds+getString(R.string.diamond_unit));
                break;
            case HANDLER_REFRESH_MSG_COUNT:
                updateMsgCount();
                break;
            default:
                break;
        }
    }


    /**
     * 余额事件：进入房间送礼成功，退出房间时或充值成功触发
     */
    @Subscribe
    public void onUpdateBalance(OnUpdateBalance event){
        if(mUser!=null){
            mUser.setMoney(event.getCurrentBalance() + "");
        }
        diamonds=event.getCurrentBalance();
        handler.sendEmptyMessage(HANDLE_UPDATE_DIAMONDS);
    }

    /**
     * 兑换事件：兑换成功触发,兑换会扣除当前收益，所以要更新收益显示值
     */
    @Subscribe
    public void onTicketCountExchange(OnTicketExchanged event){
        if(mUser!=null){
            if(event.isTotal()){
                tickets=event.getVote();
            }else{
                tickets=tickets-event.getVote();
            }
            if(tickets<0){
                tickets=0;
            }
            mUser.setIncome(tickets+"");
            handler.sendEmptyMessage(HANDLE_UPDATE_TICKETS);
        }
    }

    /**
     * 信息编辑事件：头像、昵称、性别编辑成功时触发
     */
    @Subscribe
    public void onEditSuccess(UserEditEvent editor){
        if(editor==null||editor.getOpera()==-1){
            return;
        }
        switch (editor.getOpera()){
            case UserEditEvent.UPDATE_HEAD:
                mUser.setAvatar(editor.getUser().getAvatar());
                handler.sendEmptyMessage(HANDLE_REFRESH_HEAD_VIEW);
                break;
            case UserEditEvent.UPDATE_NICK:
                mUser.setNickname(editor.getUser().getNickname());
                handler.sendEmptyMessage(HANDLE_REFRESH_NICK_VIEW);
                break;
            case UserEditEvent.UPDATE_SEX:
                mUser.setSex(editor.getUser().getSex());
                handler.sendEmptyMessage(HANDLE_REFRESH_SEX_VIEW);
                break;
            case UserEditEvent.UPDATE_INTRO:
                mUser.setIntro(editor.getUser().getIntro());
                break;
            case UserEditEvent.UPDATE_BIRTH:
                mUser.setBirthday(editor.getUser().getBirthday());
                break;
            case UserEditEvent.UPDATE_LOVE:
                mUser.setMerrage(editor.getUser().getMerrage());
                break;
            case UserEditEvent.UPDATE_ADDRESS:
                mUser.setAddress(editor.getUser().getAddress());
                break;
            case UserEditEvent.UPDATE_JOB:
                mUser.setJob(editor.getUser().getJob());
                break;
            default:
                break;
        }
    }



    /**
     * 关注操作事件：添加关注或取消关注成功时触发
     */
    @Subscribe
    public void onRefreshFollow(OnRefreshFollowCount event){
        if(event.isAttention()){//关注
            followCount++;
        }else{//取消关注
            if(followCount>0){
                followCount--;
            }
        }
        handler.sendEmptyMessage(HANDLE_REFRESH_FOLLOW);
    }

    @Override
    protected void onPermission(int requestCode) {
        editAvatar();
    }

    /**
     * 编辑头像
     */
    private void editAvatar(){
        if(mUser==null){
            return;
        }
        if(photoMenus==null){
            if (getActivity()==null){
                return;
            }
            photoMenus=new PhotoOptionMenus(this);
            photoMenus.getWindow().getAttributes().width=mScreenWidth;
        }
        photoMenus.show(true);
    }


    /**
     * 上传头像
     */
    public void uploadAvatar(String path){
        KKYUtil.log(TAG,"新头像图片路径:"+path);
        if(loadingBox.getVisibility()==View.GONE) {
            loadingBox.setVisibility(View.VISIBLE);
            uploadAni.start();
        }
        uploader.uploadCover(path);
    }

    @Override
    public void onUploadProcess(int percent) {
        //uploadPro.setText(percent+ "%");
    }

    @Override
    public void onUploadResult(int code, UploadResultInfo resultInfo) {
        if (0 == code) {
            KKYUtil.log("图片上传成功："+resultInfo.getKey());
            updateAvatar(resultInfo.getKey(), resultInfo.getUrl());
        } else {
            mainView.showTopMsg(getString(R.string.ui_upload_failed)+":"+code);
            if (loadingBox.getVisibility() == View.VISIBLE) {
                loadingBox.setVisibility(View.GONE);
                uploadAni.stop();
            }
        }
    }

    @Override
    public void onUploadResult(int code, String key) {

    }
    /**
     * 提交更新头像
     */
    private void updateAvatar(String key,final String url){
        OKHttpParam param=OKHttpParam.builder(false);
        param.remove("platform");
        param.put("avatar",key);
        OKHttp.post(HttpConfig.API_UPDATE_USER_FIELD,param.jsonParam(),TAG,new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                OKHttpResponseModel m=(OKHttpResponseModel)model;
                KKYUtil.log("提交头像成功："+m.getResponseStr());
                if (loadingBox.getVisibility() == View.VISIBLE) {
                    loadingBox.setVisibility(View.GONE);
                    uploadAni.stop();
                }
                mUser.setAvatar(url);
                MySelfInfo.getInstance().updateCacheString(getActivity(), Constants.USER_AVATAR,url);
                avatarView.setImageURI(Uri.parse(url));
            }

            @Override
            public void onErr(String errMsg) {
                if(mainView!=null){
                    mainView.showTopMsg(errMsg);
                }else{
                    return;
                }
                if (loadingBox.getVisibility() == View.VISIBLE) {
                    loadingBox.setVisibility(View.GONE);
                    uploadAni.stop();
                }
            }
        });
    }

    /**
     * 显示私信会话列表界面
     */
    public void showC2CListWin(){
        Intent c2cList=new Intent(getContext(), C2CConversationManager.class);
        startActivity(c2cList);
    }

    /**
     * 更新消息未读数
     */
    public void updateMsgCount() {
        if(countView!=null){
            if(msgCount==0){
                countView.setVisibility(View.INVISIBLE);
            }else{
                countView.setVisibility(View.VISIBLE);
            }
            countView.setText(msgCount+"");
        }
    }

    /**
     * 更新自己的信息
     */
    public void updateMySelfInfo(RoomCardInfo info){
        MySelfInfo.getInstance().setNickName(info.getNickname());
        MySelfInfo.getInstance().setAvatar(info.getAvatar());
        MySelfInfo.getInstance().setSign(info.getIntro());
        MySelfInfo.getInstance().setSex(info.getSex());
        MySelfInfo.getInstance().setAddress(info.getAddress());
        KKYUtil.log("我的信息更新,当前认证状态："+info.getApproved());
        MySelfInfo.getInstance().setVerifyState(info.getApproved());
        try {
            MySelfInfo.getInstance().setMoney(Long.parseLong(info.getMoney()));
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        try {
            MySelfInfo.getInstance().setLvl(Integer.parseInt(info.getLvl()));
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        MySelfInfo.getInstance().setMerrage(info.getMerrage());
        MySelfInfo.getInstance().writeToCache(getActivity());
    }

    /**
     * 切换语言
     */
    public void onSwitchLanguage() {
        if(handler!=null){
            handler.post(new Runnable() {
                @Override
                public void run() {
                    followTxt=getString(R.string.ui_user_follow_title);
                    fansTxt=getString(R.string.ui_user_fans_label);
                    refreshView(mInfo);
                    refreshLabelViews();
                }
            });
        }
    }

    /**
     * 用户升级
     * @param up
     */
    @Subscribe
    public void onLvUp(OnLvUp up){
        if(mUser!=null){
            mUser.setLvl(up.getNewLv()+"");
        }
        level=up.getNewLv();
        handler.sendEmptyMessage(HANDLE_UPDATE_LEVEL);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // TODO: 10/03/2017 缺少module
        if(requestCode==PhotoOptionMenus.REQUEST_PHOTO_CROP_CODE){//取到用于剪切的图片
            if(resultCode== Activity.RESULT_OK){
                //Toast.makeText(getContext(),"REQUEST_PHOTO_CROP_CODE back ok",Toast.LENGTH_LONG).show();
                if(data.getData()!=null){
                    UCrop uCrop = UCrop.of(data.getData(), Uri.fromFile(new File(getContext().getCacheDir(), MySelfInfo.getInstance().getId()+"avatar.png")));
                    uCrop.start(getContext(),this,PhotoOptionMenus.REQUEST_CROP_CODE);
                }else{
                    //Toast.makeText(getContext(),"REQUEST_PHOTO_CROP_CODE back uri null",Toast.LENGTH_LONG).show();
                }
            }else{
                localAvatar=null;
            }
        }else if(requestCode==PhotoOptionMenus.REQUEST_CAPTURE_CROP_CODE){//拍到用于剪切的图片
            if(resultCode== Activity.RESULT_OK){
                //Toast.makeText(getContext(),"REQUEST_CAPTURE_CROP_CODE back ok",Toast.LENGTH_LONG).show();
                UCrop uCrop = UCrop.of(photoMenus.getTempUri(), Uri.fromFile(new File(getContext().getCacheDir(), MySelfInfo.getInstance().getId()+"avatar.png")));
                uCrop.start(getContext(),this,PhotoOptionMenus.REQUEST_CROP_CODE);
            }else{
                localAvatar=null;
            }
        }else if(requestCode==PhotoOptionMenus.REQUEST_CROP_CODE){
            if(resultCode== Activity.RESULT_OK){
                if(data!=null){
                    Intent preview=new Intent(getContext(), PicturePreview.class);
                    preview.putExtra(PicturePreview.PREVIEW_ACTION,PicturePreview.UPLOAD);
                    localAvatar = UCrop.getOutput(data);
                    preview.setData(localAvatar);
                    startActivityForResult(preview, PhotoOptionMenus.REQUEST_PREVIEW_CODE);
                }else{
                    localAvatar=null;
                }
            }
        }else if(requestCode==PhotoOptionMenus.REQUEST_PREVIEW_CODE){
            if(resultCode== Activity.RESULT_OK){
                if(localAvatar!=null){
                    uploadAvatar(FileManager.getFilePath(getContext(),localAvatar));
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        MsgCountManager.getInstance().deleteObserver(this);
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}